package com.moon.game.config;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.moon.game.constants.GlobalConstants;


public class GlobalConfig {
	public static Element root = null;
	public static Element global = null;
	public static Map<Integer, Element> profileServerMap = new HashMap<Integer, Element>(); // ProfileServer
	public static Map<Integer, Element> dataServerMap = new HashMap<Integer, Element>(); // DataServer
	public static Map<Integer, Element> dataServerAmoebaMap = new HashMap<Integer, Element>(); // DataServer
	public static Map<Integer, Element> appServerMap = new HashMap<Integer, Element>(); // AppServer
	public static Map<Integer, Element> proxyServerMap = new HashMap<Integer, Element>(); // AppServer
	public static Map<String, Element> memcachedMap = new HashMap<String, Element>(); // Memcached
	public static Element appServerElement = null;
	public static Element proxyServerElement = null;
	public static Element dataServerElement = null;
	public static Element profileServerElement = null;
	private static Document document = null;
	private static String DB_CONFIG_FILE = "db.properties";

	/**
	 * 初始化
	 * 
	 * @param file
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static void init(String file) throws Exception {
		SAXReader reader = new SAXReader();
		document = reader.read(new File(file));
		root = document.getRootElement();
		if (root == null) {
			throw new Exception("no root node in config");
		}

		global = root.element("global");
		if (global == null) {
			throw new Exception("no global node in config");
		}

		// DataServer
		dataServerElement = root.element("DataServer");
		if (dataServerElement == null) {
			throw new Exception("no DataServer node in config");
		}
		List<Element> servers = dataServerElement.elements("server");
		for (Iterator<Element> it = servers.iterator(); it.hasNext();) {
			Element elm = it.next();
			dataServerMap.put(Integer.parseInt(elm.attributeValue("id")), elm);
		}
		
		// ProxyServer
		proxyServerElement = root.element("ProxyServer");
		if (proxyServerElement == null) {
			throw new Exception("no proxyServerElement node in config");
		}
		servers = proxyServerElement.elements("server");
		for (Iterator<Element> it = servers.iterator(); it.hasNext();) {
			Element elm = it.next();
			proxyServerMap.put(Integer.parseInt(elm.attributeValue("id")), elm);
		}

		// AppServer
		appServerElement = root.element("AppServer");
		if (appServerElement == null) {
			throw new Exception("no AppServer node in config");
		}
		servers = appServerElement.elements("server");
		for (Iterator<Element> it = servers.iterator(); it.hasNext();) {
			Element elm = it.next();
			appServerMap.put(Integer.parseInt(elm.attributeValue("id")), elm);
		}
		
		// Memcached
		Element memcached = root.element("Memcached");
		if (memcached == null) {
			throw new Exception("no Memcached node in config");
		}
		List<Element> pools = memcached.elements("pool");
		for (Iterator<Element> it = pools.iterator(); it.hasNext();) {
			Element elm = it.next();
			memcachedMap.put(elm.attributeValue("name"), elm);
		}
	}
	
	/**
	 * 生成配置文件
	 * 
	 * @param type
	 *            0、资源配置 1、全部
	 * @throws Exception
	 */
	public static void generateResConfig() throws Exception {
		String res = getResConfig();
		// 输出
		write(res);
	}

	private static String getResConfig() throws Exception {
		String driver = "com.mysql.jdbc.Driver";
		// 资源库
		String resUserName = global.element("res").attributeValue("username");
		String resPassword = global.element("res").attributeValue("password");
		String resHost = global.element("res").attributeValue("host");
		String resPort = global.element("res").attributeValue("port");
		String resName = global.element("res").attributeValue("database");
		StringBuffer sb = new StringBuffer();
		sb.append("driver=").append(driver).append("\n");
		sb.append("res_username=").append(resUserName).append("\n");
		sb.append("res_password=").append(resPassword).append("\n");
		sb.append("res_url=").append("jdbc:mysql://" + resHost + ":" + resPort + "/" + resName).append("\n\n");
		return sb.toString();
	}

	private static void write(String dbConfig) throws Exception {
		File f = new File(DB_CONFIG_FILE);
		if (!f.exists()) {
			f.createNewFile();
		}
		OutputStream os = new FileOutputStream(f);
		PrintStream ps = new PrintStream(os);
		ps.print(dbConfig);
		ps.flush();
		ps.close();
	}

	/**
	 * 根据编号取DataServer
	 * 
	 * @param id
	 * @return
	 */
	public static Element getDataServer(int id) {
		return dataServerMap.get(id);
	}

	public static Element getDataServerElement() {
		return dataServerElement;
	}
	
	/**
	 * 根据编号取ProxyServer
	 * 
	 * @param id
	 * @return
	 */
	public static Element getProxyServer(int id) {
		return proxyServerMap.get(id);
	}

	public static Element getProxyServerElement() {
		return proxyServerElement;
	}
	
	/**
	 * 根据编号取ProfileServer
	 * 
	 * @param id
	 * @return
	 */
	public static Element getProfileServer(int id) {
		return profileServerMap.get(id);
	}

	public static Element getProfileServerElement() {
		return profileServerElement;
	}

	/**
	 * 根据编号取AppServer
	 * 
	 * @param id
	 * @return
	 */
	public static Element getAppServer(int id) {
		return appServerMap.get(id);
	}

	public static Element getAppServerElement() {
		return dataServerElement;
	}

	/**
	 * 根据名称来获取memcached配置
	 * 
	 * @param poolName
	 * @return
	 */
	public static Element getMemcached(String poolName) {
		return memcachedMap.get(poolName);
	}

	/**
	 * AppServer个数
	 * 
	 * @return
	 */
	public static int getAppServerSum() {
		return appServerMap.size();
	}

	/**
	 * DataServer的个数
	 * 
	 * @return
	 */
	public static int getDataServerSum() {
		return dataServerMap.size();
	}
	
	/**
	 * ProfileServer的个数
	 * 
	 * @return
	 */
	public static int getProfileServerSum() {
		return profileServerMap.size();
	}
	
	/**
	 * ProxyServer的个数
	 * 
	 * @return
	 */
	public static int getProxyServerSum() {
		return proxyServerMap.size();
	}
	
	public static void main(String[] args) {
		try {
			init(GlobalConstants.CONFIG_FIRE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
